package com.deuwise.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.deuwise.common.utils.*;
import com.deuwise.config.oauth2.UserPermissionUtils;
import com.deuwise.system.entity.SysUser;
import com.deuwise.system.service.SysUserService;
import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.deuwise.system.entity.FileDo;
import com.deuwise.system.service.FileDoService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 *@author deuwise
 *@date 2018-11-21 11:02:18
 */
@Api(tags = "文件模块", description = "文件模块")
@RequestMapping("api/fileDo")
@RestController()
public class FileDoController extends AbstractController {

    @Value("${spring.servlet.multipart.max-file-size}")
    private  String maxFileSize;
    @ResponseBody
    @ApiOperation(value = "限定上传文件大小")
    @GetMapping("/uploadSize")
    public  R getMaxUploadSize(){
        return  R.ok(maxFileSize);
    }

    @Autowired
    private FileDoService fileDoService;
    @ResponseBody
    @ApiOperation(value = "上传文件")
    @PostMapping("/upload")
    @RequiresPermissions("sys:oss:upload")
    public R upload(@RequestParam("file")@ApiParam(value = "文件", required = true) MultipartFile file) {

        FileDo result = fileDoService.saveFile(file,getUserId());
        if(result != null){
            return R.ok(result);
        }

        return R.error();
    }

    @ApiOperation(value = "获取信息", notes = "获取信息")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @RequiresPermissions("sys:oss:all")
    public Result<FileDo> select(@PathVariable("id") String id){
       FileDo fileDo= fileDoService.selectById(id);
        return Result.ok(fileDo);
    }
    @Autowired
    UploadProperties uploadProperties;


    @ApiOperation(value = "下载文件")
    @ApiImplicitParam(name = "id", value = "文件id", dataType = "String", required = true, paramType = "path")
    @GetMapping("/download/{id}")
    @RequiresAuthentication
   /* @RequiresPermissions("sys:oss:download")*/
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {

        Set<String> permissionStr= UserPermissionUtils.getPermissionStr();
        if(permissionStr==null||!permissionStr.contains("sys:oss:download")){
            ((HttpServletResponse) response).setStatus(HttpStatus.OK.value());
            try {
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("code",44111);
                jsonObject.put("msg","无权访问");
                jsonObject.put("data",null);
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().print(jsonObject);
                return;
            } catch (IOException e) {
                // log.error(e.getMessage(), e);
            }
        }
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/octet-stream");
        FileInputStream fis = null;
        try {
            FileDo fileDo= fileDoService.selectById(id);
            if(fileDo==null){
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("code",402);
                jsonObject.put("msg","文件被删除");
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().print(jsonObject);
                return;
            }
            File file = new File(uploadProperties.getBasePath()+fileDo.getUrl());
            if(file.exists()) {
                String fileType= FileUtil.getFileType(file.getName());
                fis = new FileInputStream(file);

                response.setHeader("Content-Disposition", "attachment; filename=" +   URLEncoder.encode(fileDo.getName()+fileType,"UTF-8"));
                IOUtils.copy(fis, response.getOutputStream());
                response.flushBuffer();
            }else{
                ((HttpServletResponse) response).setStatus(HttpStatus.OK.value());
                try {
                    JSONObject jsonObject=new JSONObject();
                    jsonObject.put("code",402);
                    jsonObject.put("msg","文件不存在");
                    response.setContentType("text/html;charset=UTF-8");
                    response.getWriter().print(jsonObject);
                } catch (IOException e) {
                   // log.error(e.getMessage(), e);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @ApiOperation(value = "编辑数据")
    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @RequiresPermissions("sys:oss:all")
    public R update(@RequestBody FileDo fileDo){
        boolean isSuccess = false;
        if(null == fileDo){
            return R.error(200,"数据编辑失败，请稍后再试!");
        }
        int count = fileDoService.queryByName(fileDo.getName(),fileDo);
        if (count > 0) {
            return R.error(200, "文件名称不能重复");
        }
        isSuccess = fileDoService.updateById(fileDo);
        if (isSuccess) {
            return R.ok();
        } else {
            return R.error(200,"数据编辑失败，请稍后再试!");
        }
    }
    @ApiOperation("删除文件记录")
    @DeleteMapping("/{id}")
    @RequiresPermissions("sys:oss:del")
    public R delete(@PathVariable("id") String id){
        fileDoService.remove(id);
        return R.ok();
    }
    @Autowired
    private SysUserService userService;

    @ApiOperation(value = "获取list", notes = "获取list")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "开始页数", defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", defaultValue = "15", dataType = "int", paramType = "query")})
    @RequiresPermissions("sys:oss:list")
    public Result<Page<FileDo>> list(FileDo dictDo){
        Wrapper<FileDo> wrapper = new EntityWrapper<FileDo>();
        wrapper.orderBy("create_date",false);
        if(dictDo!=null){
            if(StringUtils.isNotBlank(dictDo.getName())){
                wrapper.like("name",dictDo.getName());
            }

            if(StringUtils.isNotBlank(dictDo.getType())){
                wrapper.eq("type",dictDo.getType());
            }
        }

        Page<FileDo> fileDoPage = fileDoService.selectPage(getPage(FileDo.class),wrapper);
        if(fileDoPage.getRecords()!=null&&fileDoPage.getRecords().size()>0){
            List<SysUser> userList=userService.selectList(null);
            for (FileDo fileDo :fileDoPage.getRecords()){
                if(StringUtils.isNotBlank(fileDo.getUserId())){
                   Optional<SysUser> optionalSysUser= userList.stream().filter(f->f.getId().equals(fileDo.getUserId())).findFirst();
                    if(optionalSysUser.isPresent()){
                        fileDo.setUserName(optionalSysUser.get().getUsername());
                    }
                }
            }
        }
        return Result.ok(fileDoPage);
    }


    @ApiOperation(value = "批量删除记录")
    @RequestMapping(value = "/deleteSelect", method = RequestMethod.POST)
    @RequiresPermissions("sys:oss:del")
    public  R deleteSelect(@ApiParam(value = "ids集合",name = "ids",required = true) @RequestParam String[] ids){
        try {
            if (ids != null && ids.length > 0) {
                for(String id:ids) {
                    fileDoService.remove(id);
                }
            }
        }catch (Exception ex){
            return  R.error("删除失败");
        }
        return  R.ok();
    }

}